package io.github.uicdb.badskill.network;

import com.mojang.logging.LogUtils;
import io.github.uicdb.badskill.PlayerSkillCapabilityProvider;
import io.github.uicdb.badskill.SkillOption;
import io.github.uicdb.badskill.SkillOptionManager;
import lombok.RequiredArgsConstructor;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.resources.ResourceLocation;
import net.minecraftforge.fml.LogicalSide;
import net.minecraftforge.network.NetworkEvent;
import org.slf4j.Logger;

import java.util.function.Supplier;

@RequiredArgsConstructor
public class LearnCheckPackage {
    private final ResourceLocation page;
    private final ResourceLocation id;
    public static LearnCheckPackage create(ResourceLocation page,ResourceLocation resourceLocation){
        return new LearnCheckPackage(page,resourceLocation);
    }    private static final Logger LOGGER= LogUtils.getLogger();
    public  void toBytes(FriendlyByteBuf buf) {
        buf.writeResourceLocation(page);
        buf.writeResourceLocation(id);
    }

    public static LearnCheckPackage create(FriendlyByteBuf buf) {
        return create(buf.readResourceLocation(),buf.readResourceLocation());
    }
    //client to server for check
    public  void handle(Supplier<NetworkEvent.Context> contextSupplier) {
        var context=contextSupplier.get();
        context.enqueueWork(() -> {
            if(context.getDirection().getReceptionSide()== LogicalSide.SERVER){
               var player= context.getSender();
               assert player!=null;
                SkillOption option= SkillOptionManager.INSTANCE.OPTIONS.get(id);
                if(option!=null){
                  player.getCapability(PlayerSkillCapabilityProvider.CAPABILITY)
                          .ifPresent(capability -> {
                            if (capability.learn(page,option,false)){
                                LOGGER.debug("learning option :{}",option.id);
                                }
                          });
                 }
            }
        });
        context.setPacketHandled(true);
    }
}
